package handler

import (
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/service"
	"fitness/go-admin/pkg/response"
	"strconv"

	"github.com/gin-gonic/gin"
)

type PlanHandler struct {
	service service.PlanService
}

func NewPlanHandler(service service.PlanService) *PlanHandler {
	return &PlanHandler{service: service}
}

// Create 创建健身计划
func (h *PlanHandler) Create(c *gin.Context) {
	var req model.PlanCreateReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	if err := h.service.Create(&req); err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, nil, "创建成功")
}

// Update 更新健身计划
func (h *PlanHandler) Update(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	var req model.PlanUpdateReq
	if err := c.ShouldBindJSON(&req); err != nil {
		response.Error(c, 400, "参数错误: "+err.Error())
		return
	}

	if err := h.service.Update(uint(id), &req); err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, nil, "更新成功")
}

// Delete 删除健身计划
func (h *PlanHandler) Delete(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	if err := h.service.Delete(uint(id)); err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.Success(c, nil, "删除成功")
}

// Get 获取健身计划详情
func (h *PlanHandler) Get(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		response.Error(c, 400, "ID格式错误")
		return
	}

	plan, err := h.service.GetByID(uint(id))
	if err != nil {
		response.Error(c, 404, "健身计划不存在")
		return
	}

	response.Success(c, plan, "获取成功")
}

// List 获取健身计划列表
func (h *PlanHandler) List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	plans, total, err := h.service.List(page, pageSize)
	if err != nil {
		response.Error(c, 500, err.Error())
		return
	}

	response.SuccessWithPage(c, plans, total, page, pageSize, "获取成功")
}
